var socket = new WebSocket("ws://localhost:8080/init");

// dom加载好，进行监听
$(function() {
	listen();
});

function emit() {
	var text = encodeScript($("#msg").val());
	var msg = {
		"message" : text,
		"color" : "#CECECE",
		"bubbleColor" : "#2E2E2E",
		"fontSize" : "12",
		"fontType" : "黑体"
	};
	msg = JSON.stringify(msg);

	socket.send(msg);
	
	$("#content").append("<kbd style='color: #" + "CECECE" + ";float: right; font-size: " + 12 + ";'>" + text +  "</kbd><br/>");
	$("#msg").val("");
}
/* 注册Socket监听事件*/
function listen() {
    /*Socket打开事件*/
	socket.onopen = function() {
		$("#content").append("<kbd>Welcome!</kbd></br>");
	};
    /*Socket收到消息事件*/
	socket.onmessage = function(evt) {
		var data = JSON.parse(evt.data);
		$("#content").append("<kbd style='color: #" + data.color + ";font-size: " + data.fontSize + ";margin-top: 10px;'>" + data.userName + " Say: " + data.message + "</kbd></br>");
	};
    /*Socket关闭事件*/
	socket.onclose = function(evt) {
		$("#content").append("<kbd>" + "Close!" + "</kbd></br>");
	};
    /*Socket错误处理事件*/
	socket.onerror = function(evt) {
		$("#content").append("<kbd>" + "ERROR!" + "</kbd></br>");
	}
}

/*监听发送消息(回车)事件*/
document.onkeydown = function(event) {
	var e = event || window.event || arguments.callee.caller.arguments[0];
	if(e && e.keyCode == 13){ // enter 键
		emit();
	}
}; 